-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.c
More file actions
58 lines (45 loc) · 1.25 KB
/
Solution.c
File metadata and controls
58 lines (45 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
// Function to sort the array (Bubble Sort)
void sortArray(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Binary Search function
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
int n, target;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the unsorted elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the target element: ");
scanf("%d", &target);
sortArray(arr, n); // Sort the array
int result = binarySearch(arr, n, target);
if (result != -1) {
printf("Element found at index %d (after sorting).\n", result);
} else {
printf("Element not found.\n");
}
return 0;
}